package com.java.service.impl;

import com.java.bean.User;
import com.java.dao.UserDao;
import com.java.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public Integer checkUsername(String username) {
        //健壮性判断 字符串是否为空
        if(!StringUtils.isEmpty(username)){
            username=username.trim();//取出两边空格
        }
        Integer count = userDao.findCountByUsername(username);
        return count;
    }

    @Override
    @Transactional
    public Integer register(User user) {
        //1.给密码加密
        user.setPassword(new Md5Hash(user.getPassword()).toString());
        //2.调用dao层业务
        return userDao.save(user);
    }

    @Override
    public User login(String username, String password) {
        //1.调用dao根据用户名查询用户信息
        User user = userDao.findByUsername(username);
        //2.判断用户名是够正确
        if(user!=null){
            //3.密码是否正确
            if(user.getPassword().equals(new Md5Hash(password).toString())){
                return user;
            }
        }
        //4.用户名或密码错误
        return null;
    }


//测试用
//    @Override
//    @Transactional
//    public List<User> findAll() {
//        List<User>list=userDao.findAll();
//        return list;
//    }
}
